import { Options } from '../entity/Options';
import { resolve } from 'node:path';
import fs from 'fs';
import fsm from 'fs/promises';
import { log } from './log';
import { getZipName } from './parameter';

export async function changeAppName(options: Options) {
  let packageJsonPath = resolve(`${options.srcDir}/package.json`);
  if (!fs.existsSync(packageJsonPath)) {
    log.error(`没有找到package.json文件: ('${packageJsonPath}')，无法解析应用名。`);
    return;
  }
  let packageJsonData = fs.readFileSync(packageJsonPath, 'utf-8');
  let packageJson = JSON.parse(packageJsonData);
  let appName = packageJson.name;
  if (!appName) {
    log.error('无法解析应用名');
    return;
  }
  let sourceAppName: string;
  let targetAppName: string;
  let zipName = getZipName(options);
  if ('win' === options.platform) {
    sourceAppName = resolve(`${options.cacheDir}/${zipName}/nw.exe`);
    targetAppName = resolve(`${options.cacheDir}/${zipName}/${appName}.exe`);
  } else if ('osx' === options.platform) {
    sourceAppName = resolve(`${options.cacheDir}/${zipName}/nwjs.app`);
    targetAppName = resolve(`${options.cacheDir}/${zipName}/${appName}.app`);
  } else if ('linux' === options.platform) {
    sourceAppName = resolve(`${options.cacheDir}/${zipName}/nw`);
    targetAppName = resolve(`${options.cacheDir}/${zipName}/${appName}`);
  } else {
    log.error(`系统无法识别: '${options.platform}'，无法修改应用名`);
    return;
  }
  await fsm.rename(sourceAppName, targetAppName);
}
